<template>
  <div class="login">
    <van-tabs
      v-model="active"
      color="#3b95fa"
      title-active-color="#3b95fa"
      title-inactive-color="#A7A7A7"
    >
      <van-tab title="手机登录">
        <div class="container">
          <van-form @submit="onSubmit">
            <div class="flex">
              <van-icon name="https://auth.zto.com/m/img/icon1.png" />
              <van-field
                v-model="telenumber"
                name="teleNumber"
                label=""
                placeholder="请输入手机号"
              />
              <van-icon
                class="close"
                name="https://auth.zto.com/m/img/delete.png"
                @click="clear"
              />
            </div>

            <div class="flex">
              <van-icon name="https://auth.zto.com/m/img/icon2.png"></van-icon>
              <van-field
                v-model="codemove"
                name="codeMove"
                label=""
                placeholder="请输入动态验证码"
              />
              <div class="codeMoveMess" @click="getTeleMoveCode">
                {{ codemovemess }}
              </div>
            </div>

            <div class="flex">
              <van-icon name="https://auth.zto.com/m/img/icon2.png"></van-icon>
              <van-field
                v-model="code2"
                name="code"
                label=""
                placeholder="请输入手机验证码"
              />
              <van-button
                class="getCode"
                plain
                hairline
                type="info"
                native-type="button"
                @click="getTeleCode"
                >{{ codeBtnMessage }}</van-button
              >
            </div>

            <div style="margin: 16px">
              <van-button round block type="info" native-type="submit"
                >提交</van-button
              >
            </div>
            <footer />
          </van-form>
        </div>
      </van-tab>

      <van-tab title="密码登录">
        <div class="container">
          <van-form @submit="onSubmit">
            <div class="flex">
              <van-icon name="https://auth.zto.com/m/img/icon3.png" />
              <van-field
                v-model="username"
                name="userName"
                placeholder="请输入用户名"
              />
              <van-icon
                class="close"
                name="https://auth.zto.com/m/img/delete.png"
                @click="clear"
              />
            </div>
            <div class="flex">
              <van-icon name="https://auth.zto.com/m/img/icon2.png"></van-icon>

              <van-field
                class="MM"
                v-model="password"
                :type="inputType"
                name="passWord"
                placeholder="请输入密码"
              />
              <van-icon
                class="showMM"
                :class="{ show: MMshow }"
                name="https://auth.zto.com/m/img/see.png"
                @click="tabShow"
              ></van-icon>
              <van-icon
                class="hideMM"
                :class="{ show: !MMshow }"
                name="https://auth.zto.com/m/img/hidden.png"
                @click="tabShow"
              ></van-icon>
            </div>
            <div style="margin: 16px">
              <van-button round block type="info" native-type="submit"
                >提交</van-button
              >
            </div>
            <footer />
          </van-form>
        </div>
      </van-tab>
    </van-tabs>
  </div>
</template>

<script>
import { getLoginData, getMoveCode, getCode } from '@/api/login'
import { Toast } from 'vant'
export default {
  name: 'Login',
  data() {
    return {
      active: 2,
      telenumber: '',
      codemove: '',
      codemovemess: '',
      code: '',
      code2: '',
      username: '',
      password: '',
      codeBtnMessage: '获取验证码',
      login: [],
      flag: true,
      // 用于判断是否需要rap2验证
      testFlag: false,
      // 用于判断名密文显示
      MMshow: false,
      inputType: this.MMshow ? 'text' : 'password',
      rule: /^1(3[0-9]|4[01456879]|5[0-3,5-9]|6[2567]|7[0-8]|8[0-9]|9[0-3,5-9])\d{8}$/
    }
  },
  created() {
    // 登录信息数据
    getLoginData().then((res) => {
      // this.login = res.data.data
      this.login = res.data.data
      // console.log(res.data.data)
    })
    // 动态验证码
    getMoveCode().then((res) => {
      this.codemovemess = res.data.code
      console.log('动态验证码：', res.data.code)
    })
    // 手机验证码
    // getCode().then((res) => {
    //   console.log('手机验证码：', res.data.code)
    // })
  },
  computed: {
  },
  methods: {
    onSubmit(values) {
      if (this.active === 0) {
        // 手机登录
        if (values.teleNumber === '' || values.codeMove === '' || values.code === '') {
          Toast({
            message: '手机号或验证码不能为空',
            position: 'bottom'
          })
        } else {
          // 判断数据真实性
          // localStorge中的数据
          // console.log(values.codeMove.toUpperCase())
          if (localStorage.getItem('loginInfo')) {
            const loginData = JSON.parse(localStorage.getItem('loginInfo'))
            for (let i = 0; i < loginData.length; i++) {
              if (values.teleNumber === loginData[i].teleNumber && values.codeMove.toUpperCase() === this.codemovemess.toUpperCase() && values.code.toUpperCase() === this.code.toUpperCase()) {
                // 数据都相等 登录成功
                Toast({
                  message: '登陆成功',
                  position: 'bottom'
                })
                localStorage.setItem('Token', JSON.stringify({ tele: values.teleNumber, tokenInfo: 'abc', time: +new Date() }))
                this.testFlag = false
                this.$router.push('/home')
                break
              } else if (values.teleNumber === loginData[i].teleNumber && (values.codeMove.toUpperCase() !== this.codemovemess.toUpperCase() || values.code.toUpperCase() !== this.code.toUpperCase())) {
                Toast({
                  message: '验证码错误',
                  position: 'bottom'
                })
              } else {
                this.testFlag = true
              }
            }
          }

          // 存在localStorge 但找不到数据 或 不存在localStorge
          if (this.testFlag === true || !localStorage.getItem('loginInfo')) {
            // rap2 中的数据
            for (let i = 0; i < this.login.length; i++) {
              if (values.teleNumber === this.login[i].teleNumber && values.codeMove.toUpperCase() === this.codemovemess.toUpperCase() && values.code.toUpperCase() === this.code.toUpperCase()) {
                // 登录成功
                Toast({
                  message: '登陆成功',
                  position: 'bottom'
                })
                localStorage.setItem('Token', JSON.stringify({ tele: values.teleNumber, tokenInfo: 'abc', time: +new Date() }))
                this.$router.push('/home')
                break
              } else if (this.rule.test(values.teleNumber) && values.codeMove.toUpperCase() === this.codemovemess.toUpperCase() && values.code.toUpperCase() === this.code.toUpperCase()) {
                // 等同于注册账号 同时进入到主页
                if (localStorage.getItem('loginInfo')) {
                  const temp = JSON.parse(localStorage.getItem('loginInfo'))
                  temp.push(values)
                  localStorage.setItem('loginInfo', JSON.stringify(temp))
                } else {
                  const temp = []
                  temp.push(values)
                  localStorage.setItem('loginInfo', JSON.stringify(temp))
                }
                Toast({
                  message: '注册并自动登录',
                  position: 'bottom'
                })
                this.$router.push('/home')
                break
              } else {
                // 登录失败 bug!!!!!!!!!!????
                Toast({
                  message: '手机号或验证码错误',
                  position: 'bottom'
                })
              }
            }
          }
        }
      } else if (this.active === 1) {
        // 用户名密码登录
        if (values.userName === '' || values.passWord === '') {
          Toast({
            message: '用户名或密码不能为空！',
            position: 'bottom'
          })
        } else {
          // 验证
          for (let i = 0; i < this.login.length; i++) {
            if (this.login[i].userName === values.userName && this.login[i].passWord === values.passWord) {
              // console.log(123)
              Toast({
                message: '登录成功',
                position: 'bottom'
              })
              localStorage.setItem('Token', JSON.stringify({ tele: values.teleNumber, tokenInfo: 'abc', time: +new Date() }))
              this.$router.push('/home')
              break
            } else {
              Toast({
                message: '用户名或密码错误',
                position: 'bottom'
              })
            }
          }
        }
      }
    },
    getTeleCode() {
      if (this.telenumber === '') {
        Toast({
          message: '请输入手机号！',
          position: 'bottom'
        })
      } else if (this.rule.test(this.telenumber)) {
        if (this.flag === true) {
          // 获取验证码
          getCode().then((res) => {
            this.code = res.data.code
            console.log('手机验证码：', this.code)
            let temp = 60
            this.flag = false
            // 点击事件失效
            const timer = setInterval(() => {
              this.codeBtnMessage = temp + 's'
              temp--
              if (temp === 0) {
                clearInterval(timer)
                this.codeBtnMessage = '获取验证码'
                // 恢复点击效果
                this.flag = true
              }
            }, 1000)
          })
        } else {
          Toast({
            message: '验证码已发送请勿重复点击',
            position: 'bottom'
          })
        }
      } else {
        Toast({
          message: '手机号格式不正确！',
          position: 'bottom'
        })
      }
    },
    getTeleMoveCode() {
      getMoveCode().then((res) => {
        this.codemovemess = res.data.code
        console.log('动态验证码：', res.data.code)
      })
    },
    clear() {
      if (this.active === 0) {
        this.telenumber = ''
      } else {
        this.username = ''
      }
    },
    tabShow() {
      this.MMshow = !this.MMshow
      this.inputType = this.MMshow ? 'text' : 'password'
    }
  }
}
</script>

<style lang="less" scoped>
.container {
  padding: 0 0.6rem;
}

.flex {
  display: flex;
  justify-content: space-between;
  align-items: center;
  position: relative;
  margin-top: 0.5rem;
  margin-bottom: 1rem;
  .van-icon:not(.close .showMM .hideMM) {
    position: absolute;
    z-index: 1;
    left: 10px;
    top: 50%;
    transform: translateY(-50%);
    font-size: 1.2rem;
  }
  .getCode {
    width: 6.5rem;
    height: 2rem;
  }
  .close {
    font-size: 1.2rem;
  }
  .van-field {
    padding-left: 30px;
    font-size: 0.85rem;
  }
  .van-cell::after {
    border-bottom: 1px solid #333;
    width: 100%;
  }
}

.hideMM,
.showMM {
  display: none;
  position: absolute;
  right: 0;
  img {
    width: 1.3rem;
    height: 1.3rem;
  }
}
.show {
  display: block;
}
.getCode,
.close {
  position: absolute;
  right: 0.6rem;
  right: 0;
  top: 50%;
  transform: translateY(-50%);
}

.codeMoveMess {
  border: 1px solid #000;
  padding: 10px 20px;
  position: absolute;
  right: 0;
  width: 4rem;
  text-align: center;
}
</style>
